<?php
namespace com\rs\dns\service\user\impl;
use com\rs\dns\constant\UserLogTypeConstant;
use com\rs\dns\constant\UserManageConst;
use com\rs\dns\controller\api\vo\UserQuery;
use com\rs\dns\controller\api\vo\UserStateSet;
use com\rs\dns\exception\BaException;
use com\rs\dns\repository\UserListRepository;
use com\rs\dns\service\DomainService;
use com\rs\dns\service\user\UserLogService;
use com\rs\dns\service\user\UserManageService;
use com\rs\dns\utils\EncryptUtils;
use restphp\biz\PageParam;
use restphp\biz\RestPageReturn;
use restphp\exception\RestException;
use restphp\i18n\RestLangUtils;
use restphp\utils\RestClassUtils;
use restphp\utils\RestStringUtils;
use restphp\utils\RestUUIDUtil;

/**
 * Class UserManageServiceImpl
 * @package php\service\user\impl.
 */
class UserManageServiceImpl implements UserManageService {
    /**
     * @var UserListRepository
     */
    private $_userRepository;
    /**
     * @var UserLogService
     */
    private $_userLogService;
    function __construct() {
        $this->_userRepository = new UserListRepository();
        $this->_userLogService = new UserLogServiceImpl();
    }

    /**
     * 获取用户列表.
     * @param $userQuery UserQuery
     * @param $pageParam PageParam
     * @return RestPageReturn.
     */
    public function getUserList($userQuery, $pageParam) {
        $arrRule = array();
        //查询条件组合
        if (!RestStringUtils::isBlank($userQuery->getAccount())) {
            $arrRule['account'] = array(' username like ? ');
            $arrRule['account'][] = '%' . $userQuery->getAccount() . '%';
        }
        if (!RestStringUtils::isBlank($userQuery->getMobile())) {
            $arrRule['mobile'] = array(' tel like ? ');
            $arrRule['mobile'][] = '%' . $userQuery->getMobile() . '%';
        }
        if (!RestStringUtils::isBlank($userQuery->getRealName())) {
            $arrRule['realName'] = array(' realName like  ? ');
            $arrRule['realName'][] = '%' . $userQuery->getRealName() . '%';
        }
        if (!RestStringUtils::isBlank($userQuery->getVerify())) {
            $arrRule['verify'] = $userQuery->getVerify();
        }
        $arrParam['rule'] = $arrRule;
        $arrParam['page_param'] = $pageParam;
        $arrParam['order'] = ' order by verify, id asc ';

        return $this->_userRepository->getPageReturn($arrParam);
    }

    /**
     * 添加用户.
     * @param $arrNewUser
     * @return mixed|void
     * @throws RestException
     */
    public function addUser($arrNewUser)
    {
        $arrNewUser['password'] = EncryptUtils::encodePassword($arrNewUser['password']);
        $arrNewUser['regtime'] = date('Y-m-d H:i:s');
        //查询用户名是否重复。
        $arrExistAccountRule = array(
            'rule' => array(
                'username' => $arrNewUser['username']
            )
        );
        $nExistAccount = $this->_userRepository->count($arrExistAccountRule);
        if ($nExistAccount > 0) {
            throw new RestException(UserManageConst::ACCOUNT_EXIST, UserManageConst::ACCOUNT_EXIST_CODE);
        }
        //查询手是否重复
        $arrExistPhone = array(
            'rule' => array(
                'tel' => $arrNewUser['tel']
            )
        );
        $nExistPhone = $this->_userRepository->count($arrExistPhone);
        if ($nExistPhone > 0) {
            throw new RestException(UserManageConst::PHONE_EXIST, UserManageConst::PHONE_EXIST_CODE);
        }
        $this->_userRepository->insert($arrNewUser);
    }

    /**
     * 修改用户.
     * @param $strUserId
     * @param $arrUpdate
     * @return mixed|void
     * @throws RestException
     */
    public function modifyUser($strUserId, $arrUpdate) {
        $update = array(
            'isadmin' => $arrUpdate['isadmin'],
            'realname' => $arrUpdate['realname'],
            'tel' => $arrUpdate['tel'],
            'verify' => $arrUpdate['verify'],
            'username' => $arrUpdate['username'],
            'soanum' => $arrUpdate['soanum'],
            'rrnum' => $arrUpdate['rrnum']
        );
        if (isset($arrUpdate['password']) && !RestStringUtils::isBlank($arrUpdate['password'])) {
            $update['password'] = EncryptUtils::encodePassword($arrUpdate['password']);
        }

        //账号重复
        $arrExistAccount = array(
            'rule' => array(
                'ID' => array(' ID<>? ', $strUserId),
                'username' => $arrUpdate['username']
            )
        );
        $nExistAccount = $this->_userRepository->count($arrExistAccount);
        if ($nExistAccount > 0) {
            throw new BaException(UserManageConst::ACCOUNT_EXIST);
        }

        //手机重复
        $arrExistPhone = array(
            'rule' => array(
                'id' => array('id<>?', $strUserId),
                'tel' => $arrUpdate['tel']
            )
        );
        $nExistPhone = $this->_userRepository->count($arrExistPhone);
        if ($nExistPhone > 0) {
            throw new RestException(UserManageConst::PHONE_EXIST, UserManageConst::PHONE_EXIST_CODE);
        }

        //用户是否存在
        $user = $this->_userRepository->findOneByUserId($strUserId);
        if (null == $user) {
            throw new RestException(UserManageConst::USER_NOT_EXIST, UserManageConst::USER_NOT_EXIST_CODE);
        }

        $arrRule = array(
            'id' => $strUserId
        );
        $this->_userRepository->update($update, $arrRule);
    }

    /**
     * 删除用户.
     * @param $strUserId
     * @return mixed|void
     * @throws RestException
     */
    public function deleteUser($strUserId) {
        $userBean = $this->_userRepository->findOneByUserId($strUserId);
        if (null == $userBean) {
            throw new RestException(UserManageConst::USER_NOT_EXIST, UserManageConst::USER_NOT_EXIST_CODE);
        }

        $arrRule = array(
            'ID' => $strUserId
        );
        $this->_userRepository->delete($arrRule);

        //删除域名及解析记录
        DomainService::clearByUsernames(array($userBean->getUsername()));
    }

    /**
     * 批量删除用户.
     * @param array $arrId
     * @return mixed|void
     */
    public function deleteUserBatch($arrId) {
        $strDelRule = '';
        $arrSqlParam = array();
        foreach ($arrId as $id) {
            $strDelRule .= ('' == $strDelRule ? '' : ',') . '?';
            $arrSqlParam[] = $id;
        }
        $arrRule = array(
            "k" => array(
                " id in ({$strDelRule}) ",
                $arrSqlParam
            )
        );

        //找出所选的用户账号，用于删除域名和解析记录
        $arrParams = array(
            'output' => 'username',
            'rule' => $arrRule
        );
        $userList = $this->_userRepository->select($arrParams);
        $arrUser = array();
        foreach ($userList as $user) {
            $arrUser[] = $user['username'];
        }

        //删除用户
        $this->_userRepository->delete($arrRule);

        //删除域名及解析记录
        DomainService::clearByUsernames($arrUser);
    }

    /**
     * 批量设置用户状态.
     * @param UserStateSet $userStateSet
     * @return mixed|void
     */
    public function batchSetState($userStateSet) {
        $strDelRule = '';
        $arrSqlParam = array();
        foreach ($userStateSet->getUserIdList() as $id) {
            $strDelRule .= ('' == $strDelRule ? '' : ',') . strval($id);
            $arrSqlParam[] = $id;
        }
        $arrRule = array(
            "k" => array(
                " id in ({$strDelRule}) ",
                $arrSqlParam
            )
        );
        $arrUpdate = array(
            'verify' => $userStateSet->getVerify()
        );
        $this->_userRepository->update($arrUpdate, $arrRule);
    }


}